var express = require('express');
var router = express.Router();
const jwt = require("jsonwebtoken");
// const multiparty = require('multiparty');
const { userModel } = require('../model/zjb_model')
const { MemberModel } = require('../model/cxy_model')
const { pbkdf2, randomBytes } = require('node:crypto');

router.post('/login', async (req, res) => {
	let openid = req.body.openid
	await userModel.updateOne({ openid }, { name: req.body.name, avater: req.body.avater })
	let isuser = await userModel.find({ openid })
	let data
	if (isuser.length == 0) {
		data = await userModel.create(req.body)
	} else {
		data = isuser[0]
	}
	res.send({
		code: 200,
		msg: "登录成功",
		data
	})
})

router.post("/pclogin", async (req, res) => {
	let body = req.body
	pbkdf2(body.password, "zjbyzbcxyzhynb666xiaosiwolehahah", 100000, 64, 'sha512', async (err, derivedKey) => {
		if (err) throw err;
		body.password = derivedKey.toString("hex")
		let data = await MemberModel.find(body)
		if (data.length > 0) {
			let token =
				"Bearer " +
				jwt.sign(body, "lin", { expiresIn: 10 * 600000 });
			res.send({
				code: 200,
				data,
				token,
				msg: "登录成功"
			})
		} else {
			console.log(body)
			await MemberModel.updateOne({shou:body.shou},body)
			res.send({
				code: 401,
				data,
				msg: "登录失败"
			})
		}
	})
})


module.exports = router;